#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
  int pipefd[2] = {0};
  if(pipe(pipefd) != 0){
    perror("pipe error!");
    return 1;
  }
  //0：读取端  1：写入端
  printf("pipefd[0]:%d\n",pipefd[0]);
  printf("pipefd[1]:%d\n",pipefd[1]);

  if(fork() == 0){//child完成写入
    close(pipefd[0]);//子进程关闭读端

    const char* msg = "hello Linux!";
    while(1){
      write(pipefd[1], msg, strlen(msg));
      sleep(1);
    }
    exit(0);
  }
  //parent完成读取
  close(pipefd[1]);//父进程关闭写端
  while(1){
    char buffer[64] = {0};
    ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
    if(s == 0){//意味着子进程退出了
      printf("child quit\n");
      break;
    }
    else if( s > 0 ){
      buffer[s] = 0;
      printf("child say to father# %s\n",buffer);
    }
    else{
      printf("read error\n");
      break;
    }
  }
  return 0;
}
